package com.myBlast.server;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.commons.httpclient.NameValuePair;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DefaultLogger;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.ProjectHelper;


/**
 * This is a helper class for PipeLineClient. 
 * PipeLineClient accepts the arguments and then delegates the responsibility to run the underlying Ant script
 * for running BLAST to this class. 
 * @author Parit Bansal
 *
 */
public class AntHandler 
{

	/**
	 * This method runs the Ant file.
	 * @param buildFile The File object over the build.xml file
	 * @param properties A List of NameValue objects containing various properties and their values
	 * 					 to be set.
	 * @param targetName The target to run
	 * @return true if ant runs successfully else false
	 * @throws IOException
	 */
	public boolean runAnt(File buildFile, List<NameValuePair> properties, String targetName) throws IOException 
	{
		boolean result = true;
		DefaultLogger consoleLogger = new DefaultLogger();
		consoleLogger.setErrorPrintStream(System.err);
		consoleLogger.setOutputPrintStream(System.out);
		consoleLogger.setMessageOutputLevel(Project.MSG_INFO);
		
		
		Project p = new Project();
		p.addBuildListener(consoleLogger);
		
		try
		{
			p.fireBuildStarted();
			p.setUserProperty("ant.file", buildFile.getAbsolutePath());
			if (properties != null)
			{
				for (NameValuePair pair : properties)
				{
					p.setUserProperty(pair.getName(),pair.getValue());
				}
			}
			p.init();
			ProjectHelper helper = ProjectHelper.getProjectHelper();
			p.addReference("ant.projectHelper", helper);
			helper.parse(p, buildFile);
			if (targetName == null) targetName = p.getDefaultTarget(); 
			p.executeTarget(targetName);
		}
		catch (BuildException e) 
		{
			p.fireBuildFinished(e);
			result = false;
		}
		return result;
	}
}// RequestHandler

